var listen = listen || {};

 

listen.startDragging = function(E){
	eyeMoveDelta[0] = eyeMoveDelta[2] = E.x;
	eyeMoveDelta[1] = eyeMoveDelta[3] = E.y;	
	eyeMoveDelta[4] = eyeMoveDelta[10] = eyeAngle[0];
	eyeMoveDelta[5] = eyeMoveDelta[11] = eyeAngle[1];
	eyeMoveDelta[6] = eyeR;
	eyeMoveDelta[7] = viewCenter[0];
	eyeMoveDelta[8] = viewCenter[1];
	eyeMoveDelta[9] = viewCenter[2];
	if(mouseCursor == "NONE"){
		cubeClient.cursor = cubeO3d.Cursor.NONE;
		}else if(mouseCursor == "POINTER"){
			cubeClient.cursor = cubeO3d.Cursor.POINTER;
			}else if(mouseCursor == "MOVE"){
				cubeClient.cursor = cubeO3d.Cursor.MOVE;
				}else{
					cubeClient.cursor = cubeO3d.Cursor.DEFAULT;
					}
	
	if(E.button == 0 && mouseMode ){
		mouseButton["leftButton"] = true;
		frameActiveNow.dragFrame = [];//清楚可拖动的对话框索引
		
		mouseButton["frameTouchStart"] = false;
		if(frameActiveNow[0]){
			for (var n = frameActiveNow.length-1;n>=0;n--){
				//如果在循环中触碰某项菜单组，就不要再检测其他的菜单组。
				if(mouseButton["frameTouchStart"]){break;}
				
				for (var nSub = frameActiveNow[n].length-1;nSub>=0;nSub--){
					var testFrame = frameActiveNow[n][nSub];
						if(E.x>testFrame.x && 
						   E.x-testFrame.x < testFrame.width &&
						   E.y>testFrame.y && 
						   E.y-testFrame.y < testFrame.height){
							mouseButton["frameTouchStart"] = true;
							//如果这个被击中的菜单组不是最高的那个，就把它的层级升到最高,并执行函数。
							if(n != frameActiveNow.length-1){
								frameActiveNow.sortUp(n);
								if(nSub==frameActiveNow[frameActiveNow.length-1].length-1){
									//这里写点中菜单组下最后一个（激活状态）的对话框时 的响应
									frameActiveNow[frameActiveNow.length-1][nSub].checkMouseDown([E.x,E.y])
									}
								}
							else if(nSub==frameActiveNow[n].length-1){
								//这里写点中菜单组下最后一个（激活状态）的对话框时 的响应
								frameActiveNow[n][nSub].checkMouseDown([E.x,E.y])
								}
							break;
						}
					}
				}
 			}
		
		if (menuMassLevelArray.length!=0){
				menu.formatAlpha(menuMass[menuMassLevelArray[0]]);
				menuMass[menuMassLevelArray[0]].transform.parent = null;
				menuMass[menuMassLevelArray[0]].centerX = menuMass[menuMassLevelArray[0]].centerY = undefined;		
				menuMassLevelArray = [];
			}
		else if(!mouseButton["frameTouchStart"]){
				if(mouseButton["moveMode"]){
					touchPicked = picker.touchPickedFace(E);
					if (touchPicked){
							 deltaCubesKey = [0,0,0];
							 creator.freezeMatrixCubeAndMass();
							 growthBounding = worker.buttPlaneBunding(touchPicked[4],touchPicked[3]);
							 }
							else{
								worker.openCloseMoveMode();
								creator.removeAllFrames();
								cubeSelectNow = [];
								//如果没有点击已选cube直接进入涂抹选择模式
								var pickJustNow = picker.pick(E);
								drawCubePlan = picker.initDrawPlan(pickJustNow);
								mouseButton["drawSelect"] = true;
								}
				}
				else if(mouseButton["pickColorMode"]){
					var pickJustNow = picker.virtualPick(E);
					getColorByPick(pickJustNow);
					//加入一些关联操作的代码
				}
				else if(mouseButton["penMode"]){
					//进入画笔模式，先进行一次虚拟点点选，如果点中，开始绘画（初始化绘画平面）；
					var pickJustNow = picker.virtualPick(E);
					if(pickJustNow){
						//下回要加入一个点中组的时候的分支情况。
						pickJustNow[2].changeColor(defultValue.red,
												   defultValue.green,
												   defultValue.blue,
												   defultValue.alpha);
						drawCubePlan = picker.initDrawPlan(pickJustNow);
						}
						else{
							var checkNum = totalColorUnitFrame.checkActiveNum();
							if(checkNum != undefined){
								mouseButton["penMode"] = false;
								totalColorUnitFrame.delActiveNow();
								
								mouseCursor="DEFAULT";
								customizeCursor.changeFrameAlpha([0]);

								dialog.moveDialogTo(totalColorUnitFrame,-totalColorUnitFrame.width,0);
								dialog.tips.hidden();
								}
							}
					}
					else{
						touchPicked = picker.touchPickedFace(E);
						//生成模式touchPicked[5]中记录是否此次碰撞检测选中了之前已被激活的面。
						if(touchPicked && !touchPicked[2][0] && touchPicked[5]){
							deltaCubesKey = [0,0,0];
							creator.freezeSelect();
							growthBounding = worker.buttPlaneBunding(touchPicked[4],touchPicked[3]);
							}
						else if(touchPicked && touchPicked[2][0]){
								//移动模式
								deltaCubesKey = [0,0,0];
								creator.freezeMatrix();
								growthBounding = worker.buttPlaneBunding(touchPicked[4],touchPicked[3]);
								}
								//涂抹选择模式
						else {
							var pickJustNow = picker.pick(E);
							drawCubePlan = picker.initDrawPlan(pickJustNow);
							mouseButton["drawSelect"] = true;
							//首次点击的提示
							if(pickJustNow && !mouseButton["firstDrawSelected"]){
								dialog.tips.showBy("很好，你已经选中了一个面。下面我们来尝试创建出自己的方块。把鼠标放到刚被选中的面上，会有一个提示箭头。这时候左键点击这个面不要松开，沿着箭头提示的方向把它向外拉出来，新的方块就会长出来。试试看吧，奇迹就要诞生了！",800);
								mouseButton["firstDrawSelected"] = true;
								}
							}
					}
				}
				
		}
		else if (E.button == 1){
			mouseButton["move"] = true;
			}
		else if (E.button == 2){
			mouseButton["rotation"] = true;
			}
	cubeDragging = true;
	}

listen.drag = function(E){
		eyeMoveDelta[2] = E.x;
		eyeMoveDelta[3] = E.y;
		if(mouseCursor == "NONE"){
			cubeClient.cursor = cubeO3d.Cursor.NONE;
			
			
			customizeCursor.moveTo([E.x, E.y]);
			
			}else if(mouseCursor == "POINTER"){
				cubeClient.cursor = cubeO3d.Cursor.POINTER;
				}else if(mouseCursor == "MOVE"){
					cubeClient.cursor = cubeO3d.Cursor.MOVE;
					}else{
						cubeClient.cursor = cubeO3d.Cursor.DEFAULT;
						}
		
			mouseButton["frameTouchOver"] = false;
			if(!cubeDragging && frameActiveNow[0]){
			for (var n = frameActiveNow.length-1;n>=0;n--){
					//如果在循环中触碰某项菜单组，就不要再检测其他的菜单组。
					if(mouseButton["frameTouchOver"]){break;}
					
					for (var nSub = frameActiveNow[n].length-1;nSub>=0;nSub--){
						var testFrame = frameActiveNow[n][nSub];
							if(E.x>testFrame.x && 
							   E.x-testFrame.x < testFrame.width &&
							   E.y>testFrame.y && 
							   E.y-testFrame.y < testFrame.height){
								mouseButton["frameTouchOver"] = true;
								var touchFrameMassNum = n;
								if(nSub==frameActiveNow[n].length-1){
								//这里写点中菜单组下最后一个（激活状态）的对话框时 的响应
									frameActiveNow[n][nSub].checkMouseOver([E.x,E.y]);
									}
								else{
								//这里写没有点中菜单组下最后一个（激活状态）的对话框时 的响应
									}
								break;
							}
							else{//没有经过
								testFrame.allActiveLeave();
								
								}
						}
					}
				}
				
			if(mouseButton["leftButton"] && frameActiveNow.dragFrame[0]){
				for (var n = 0;n < frameActiveNow.dragFrame.length ;n++){
						frameActiveNow.dragFrame[n][0].checkMouseDrag([E.x,E.y,
																	   frameActiveNow.dragFrame[n][1],
																	   frameActiveNow.dragFrame[n][2]]);
					}
				}
			
		if (menuMassLevelArray.length!=0 ){
			menu.active(E,menuMassLevelArray[0]);
			}
		else if(!mouseButton["frameTouchOver"]){
			if (mouseButton["move"]){
				eyeTarAmong = null;
				var rY = (eyeMoveDelta[3] - eyeMoveDelta[1]) * moveFactor * eyeMoveDelta[6] * 0.1;
				var aY = eyeMoveDelta[4] - PI;
				var bY = PI/2 - eyeMoveDelta[5];
				var rX = (eyeMoveDelta[0] - eyeMoveDelta[2]) * moveFactor * eyeMoveDelta[6] * 0.1;
				var aX = eyeMoveDelta[4] - PI/2;
				var targetZ = rY*Math.cos(bY)*Math.sin(aY) + rX*Math.sin(aX) + eyeMoveDelta[9];
				var targetY = rY*Math.sin(bY) + eyeMoveDelta[8];
				var targetX = rY*Math.cos(bY)*Math.cos(aY) + rX*Math.cos(aX) + eyeMoveDelta[7];
				view.moveViewCenter([targetX,targetY,targetZ]);
				}
				else if (mouseButton["rotation"]){
					eyeTarAmong = null;
					var angleAfter = new Array;
					angleAfter[0]  = (eyeMoveDelta[2]-eyeMoveDelta[0]) * moveFactor + eyeMoveDelta[4];
					var angleTest =  (eyeMoveDelta[3]-eyeMoveDelta[1]) * moveFactor + eyeMoveDelta[5];
					if (angleTest >= 0){
						angleAfter[1] = Math.abs(angleTest)>PI/2 - 0.001 ? PI/2 - 0.001: angleTest;
						}
						else{
							angleAfter[1] = Math.abs(angleTest)>PI/2 - 0.001 ? -PI/2 + 0.001: angleTest;
							}
					view.angleRotate(angleAfter);
					}
					else if (mouseButton["drawSelect"]){
						if(drawCubePlan){
							picker.drawSelectCube(drawCubePlan,E);
							}
						}
						else if(mouseButton["moveMode"]){
							if(touchPicked){
								creator.cubeMove(touchPicked[4],touchPicked[3],growthBounding,E.x,E.y);
								moveArrow.moveByPick(touchPicked,deltaCubesKey[0]);
								}
							else{
								var pickForDisplay = picker.touchPickedFace(E);
								listen._displayArrowByPick(pickForDisplay);
								}
							}
						else if(touchPicked && !touchPicked[2][0]){
							creator.cubeGrowth(touchPicked[4],touchPicked[3],growthBounding,E.x,E.y);
							growthArrow.moveByPick(touchPicked,deltaCubesKey[1]);
							}
						else if(touchPicked && touchPicked[2][0]){
							creator.cubeMove(touchPicked[4],touchPicked[3],growthBounding,E.x,E.y);
							moveArrow.moveByPick(touchPicked,deltaCubesKey[0]);
							}
						else if(mouseButton["penMode"] && E.button == 0 && cubeDragging){
							if(drawCubePlan){
								picker.drawColorToCube(drawCubePlan,E);
								}
							}
						else if(!touchPicked){
								var pickForDisplay = picker.touchPickedFace(E);
								listen._displayArrowByPick(pickForDisplay);
								}
		}
	}

listen.stopDragging = function(E){
		eyeAngle[0] = view.PiRound(eyeAngle[0]);
		eyeAngle[1] = view.PiRound(eyeAngle[1]);
		cubeDragging = false;
		moveArrow.clear();
		if(mouseCursor == "NONE"){
			cubeClient.cursor = cubeO3d.Cursor.NONE;
			}else if(mouseCursor == "POINTER"){
				cubeClient.cursor = cubeO3d.Cursor.POINTER;
				}else if(mouseCursor == "MOVE"){
					cubeClient.cursor = cubeO3d.Cursor.MOVE;
					}else{
						cubeClient.cursor = cubeO3d.Cursor.DEFAULT;
						}
		
		if (E.button == 0 && mouseMode){
			mouseButton["frameTouchStop"] = false;
			if(frameActiveNow[0]){
			for (var n = frameActiveNow.length-1;n>=0;n--){
					//如果在循环中触碰某项菜单组，就不要再检测其他的菜单组。
					if(mouseButton["frameTouchStop"]){break;}
					
					for (var nSub = frameActiveNow[n].length-1;nSub>=0;nSub--){
						var testFrame = frameActiveNow[n][nSub];
							if(E.x>testFrame.x && 
							   E.x-testFrame.x < testFrame.width &&
							   E.y>testFrame.y && 
							   E.y-testFrame.y < testFrame.height){
								mouseButton["frameTouchStop"] = true;
								var touchFrameMassNum = n;
								if(nSub==frameActiveNow[n].length-1){
								//这里写点中菜单组下最后一个（激活状态）的对话框时 的响应
									frameActiveNow[n][nSub].checkMouseUp([E.x,E.y])
									}
								else{
								//这里写没有点中菜单组下最后一个（激活状态）的对话框时 的响应
									}
								break;
							}
						}
					}
				}
	//鼠标左键按下或者右键抬起没有点中菜单的时候执行，或者在右键抬起时虽然点中菜单，但是已经在生成模式或移动模式中改变cube，也同样执行。
			if((!mouseButton["frameTouchStop"] && !mouseButton["frameTouchStart"])||
				(mouseButton["frameTouchStop"] && (mouseButton["growth"]||mouseButton["moved"]))){
					if (mouseButton["growth"]){
						creator.deleUnGrowth();
							//清除全部的选择
						creator.removeAllFrames();
						cubeSelectNow = [];
						var thisMass = cubeSelect[cubeSelect.length-1];
						var nNum = thisMass.length;
						for(var nCube=0;nCube < nNum;nCube++){
							if(!thisMass[nCube].boundingBox){
								thisMass[nCube].comBounding();
								}
							}
						worker.reAddBoundingByChild(cubeSelect[cubeSelect.length-1]);
						
						
						//初次生成后的提示
							if(mouseButton["growth"] && !mouseButton["firstGrowthed"]){
								dialog.tips.showBy("就是这样，接下来请自己尝试更多的操作，还有更多的奇迹等待你来实现！开始分享和发掘你的想象力吧。",400);
								mouseButton["firstGrowthed"] = true;
								}
								
								
						mouseButton["growth"] = false; 
						}
					else if (mouseButton["moved"]){
							creator.upDateMovedInfo(freezeSelectMatrix[0],touchPicked[3]);
							//清除全部的选择
							creator.removeAllFrames();
							cubeSelectNow = [];
							for(var nMass=freezeSelectMatrix[0].length-1;nMass>=0;nMass--){
								//暂时使用这种重新计算的方式，速度比较慢，以后能加入对bounding的直接变换会快很对。
								worker.reComputeBounding(freezeSelectMatrix[0][nMass]);
								}
						worker.reAddBoundingByChild(cubeSelect[cubeSelect.length-1]);
						mouseButton["moved"] = false;
						}
					else if(!mouseButton["drawSelect"] && !mouseButton["penMode"]){
							picker.pick(E);
						}
					touchPicked = null;
					}
				}
		else if (E.button == 2){
					menu.cancel();
					if (menuMassLevelArray.length ==0 && 
						Math.abs(eyeMoveDelta[0]-E.x) < 3 && 
						Math.abs(eyeMoveDelta[1]-E.y) < 3 && mouseMode){
						var menuNo;
						if(cubeSelectNow.length == 0){
							menuNo = 0;
							}
						else{
							var pickInfo = picker.touchPickedFace(E);
							if (!pickInfo){menuNo = 1;}
							else{
								var massExist = false;
								var cubeExist = false;
								for(var n=0;n < cubeSelectNow.length;n++){
									if(cubeSelectNow[n][2][0]){massExist = true;}
									else{cubeExist = true;}
									}
								if(massExist && !cubeExist){menuNo = 2;}
								else if(!massExist && cubeExist){menuNo = 3;}
								else if(!pickInfo[2][0]){menuNo = 3;}
								else {menuNo = 4;}
								}
							}
				menuMass[menuNo].transform.parent = menuMass.transform;
				menu.active(E,menuNo);
				}
			}
		//关闭所有的开关。
		mouseButton["leftButton"] = false;//代表左键按下的开关，listen.drag函数中使用。因为drag的触发取不到左右键
		mouseButton["zoom"] = false;
		mouseButton["move"] = false;
		mouseButton["rotation"] = false;
		mouseButton["drawSelect"] = false;
		mouseButton["directMove"] = false;
		mouseButton["picking"] = false;
		mouseButton["zoomfalse"] = false;
		//stopAccelera();
	}

listen.scrollCubes = function(E){
	//清除一下坐标轴显示，否者有时会有Bug
	moveArrow.clear();
	growthArrow.clear();

	if(!mouseButton["zoomfalse"]){
			mouseButton["zoomfalse"] = true;
			var zoom = (E.deltaY>0) ? 1/zoomFactor : zoomFactor;
			view.zoomEyeR(eyeR*zoom,15);
			eyeTarAmong = null;
		}
	}

//根据碰撞信息来显示或者清除 箭头提示，onlyDisplayMove是一个布尔值，为true表示只显示移动箭头提示，在移动模式时使用。
listen._displayArrowByPick = function(pickInfo){
	if(pickInfo){
		if(mouseButton["moveMode"]){
			moveArrow.displayByPick(pickInfo,true);
			growthArrow.clear();
			}
		else if(pickInfo[2][0]){
			moveArrow.displayByPick(pickInfo);
			growthArrow.clear();
			}
		else if(pickInfo[5]){
			growthArrow.displayByPick(pickInfo);
			moveArrow.clear();
			}
		else{
			moveArrow.clear();
			growthArrow.clear();
			}
		}
	else{
		moveArrow.clear();
		growthArrow.clear();
		}
	}	

listen.keyDown = function(E){//应该给相应的开关，否则会出错
		//alert(E.keyCode);
		if(E.ctrlKey){
			switch(E.keyCode){
				case 65://a
					worker.selectAllExist();
					menu.cancel();
					break;
				case 83://s
					document.getElementById("dataForm").cubeData.value = 
											worker.save(cubeSelect[cubeSelect.length-1]);
					menu.cancel();
					break;
				}
		}	
		else{	
			switch(E.keyCode){
				case 80://p
					worker.capture();
					setTimeout(function(){resizeClient();},50);
					break;
				case 76://l
					saveCapToServer()
					break;
				case 32: //空格
					view.resetView();
					menu.cancel();
					break;
				case 90://z
					 undoCube();
					 menu.cancel();
					break;
				case 82://r
					creator.insertCubeOri();
					menu.cancel();
					break;
				case 77://m
					worker.openCloseMoveMode();
					menu.cancel();
					break;
				case 79://o
					/*var createString = document.getElementById("createString").value;
					worker.create(createString);
					menu.cancel();*/
					break;
				case 46://del
					worker.removeCubes();
					menu.cancel();
					break;
				case 71://g
					worker.packCube();
					menu.cancel();
					break;
				case 85://u
					worker.unPackCube();
					menu.cancel();
					break;
				case 80://p
					if(!mouseButton["penMode"]){
						mouseButton["penMode"] = true;
						//dialog.createTotalColorUnit();
						}
						else{
							mouseButton["penMode"] = false;
							}
					break;
				case 67://c
					worker.changeCube();
					menu.cancel();
					break;
				case 38:
					menuFunction.menuReviewUp();
					break;
				case 37:
					menuFunction.menuReviewLeft();
					break;
				case 40:
					menuFunction.menuReviewDown();
					break;
				case 39:
					menuFunction.menuReviewRight();
					break;
				case 229:
					dialog.tips.showBy("是不是把输入法打开了？",500);
				break;
				}
			}
			
			
		if(E.altKey){
			if(E.keyCode != 18){
				alert(E.keyCode);
				}
			}

	}


listen.editMass = function(E){
			mouseButton["frameTouchDouble"] = false;
			if(frameActiveNow[0]){
				for (var n = 0;n < frameActiveNow.length ;n++){
					//如果在循环中触碰某项菜单组，就不要再检测其他的菜单组。
					if(mouseButton["frameTouchDouble"]){break;}
					
					for (var nSub = frameActiveNow[n].length-1;nSub>=0;nSub--){
						var testFrame = frameActiveNow[n][nSub];
							if(E.x>testFrame.x && 
							   E.x-testFrame.x < testFrame.width &&
							   E.y>testFrame.y && 
							   E.y-testFrame.y < testFrame.height){
								mouseButton["frameTouchDouble"] = true;
								var touchFrameMassNum = n;
								if(nSub==frameActiveNow[n].length-1){
								//这里写点中菜单组下最后一个（激活状态）的对话框时 的响应
									//frameActiveNow[n][nSub].checkMouseDb([E.x,E.y])
									}
								else{
								//这里写没有点中菜单组下最后一个（激活状态）的对话框时 的响应
									}
								break;
							}
						}
					}
				}

	if(!mouseButton["frameTouchDouble"]){
		var deltaX = Math.abs(E.x - eyeMoveDelta[0]);
		var deltaY = Math.abs(E.y - eyeMoveDelta[1]);
		if (deltaX < 3 && deltaY < 3){
				creator.removeAllFrames();
				cubeSelectNow = [] ;
				picker.pick(E);
				var selectArea = cubeSelect[cubeSelect.length-1];
				if(!cubeSelectNow[0]){
					if(cubeSelect.length!=1){
						var just = cubeSelect.pop();
						worker.changeOtherAlpha(cubeSelect[cubeSelect.length-1],0.1,just);
						}
					creator.removeAllFrames();
					cubeSelectNow = [];
					view.resetView();
					return;
					}
				
				if(cubeSelectNow[0][2][0]){
					cubeSelect.push(cubeSelectNow[0][2]);	
					worker.changeOtherAlpha(cubeSelect[cubeSelect.length-1],0.1);
					creator.removeAllFrames();
					cubeSelectNow = [];
					view.resetView();
					}
					else{
						view.resetCentreBySele();
						}
			}
		}
	}



